<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-white">播放历史</h1>
      <button
        v-if="history.length > 0"
        @click="clearHistory"
        class="btn-secondary"
      >
        <i class="fas fa-trash mr-2"></i>清空历史
      </button>
    </div>

    <!-- 统计信息 -->
    <div v-if="history.length > 0" class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
      <div class="card p-4">
        <div class="text-2xl font-bold text-primary-400">{{ history.length }}</div>
        <div class="text-sm text-gray-400">总播放数</div>
      </div>
      <div class="card p-4">
        <div class="text-2xl font-bold text-primary-400">{{ totalWatchTime }}</div>
        <div class="text-sm text-gray-400">总观看时长</div>
      </div>
      <div class="card p-4">
        <div class="text-2xl font-bold text-primary-400">{{ todayWatchCount }}</div>
        <div class="text-sm text-gray-400">今日播放</div>
      </div>
    </div>

    <!-- 历史列表 -->
    <div v-if="history.length > 0" class="space-y-4">
      <div
        v-for="item in history"
        :key="item.mediaId"
        class="card p-4 hover:bg-gray-700 transition-colors"
      >
        <div class="flex items-center space-x-4">
          <!-- 缩略图 -->
          <div class="w-32 h-20 bg-gray-700 rounded flex items-center justify-center">
            <i class="fas fa-play text-gray-500 text-2xl"></i>
          </div>

          <!-- 信息 -->
          <div class="flex-1">
            <h3 class="text-lg font-medium text-white mb-1">{{ item.title }}</h3>
            <p class="text-sm text-gray-400 mb-2">{{ item.url }}</p>
            <div class="flex items-center space-x-4 text-sm text-gray-400">
              <span>
                <i class="fas fa-clock mr-1"></i>
                上次播放: {{ formatDate(item.lastPlayed) }}
              </span>
              <span>
                <i class="fas fa-history mr-1"></i>
                进度: {{ formatTime(item.lastPosition) }} / {{ formatTime(item.duration || 0) }}
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex items-center space-x-2">
            <button
              @click="resumePlay(item)"
              class="btn-primary"
            >
              <i class="fas fa-play mr-1"></i>继续播放
            </button>
            <button
              @click="removeFromHistory(item.mediaId)"
              class="btn-secondary"
            >
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>

        <!-- 进度条 -->
        <div class="mt-3">
          <div class="bg-gray-700 rounded-full h-2">
            <div
              class="bg-primary-500 h-2 rounded-full transition-all duration-300"
              :style="{ width: `${getProgress(item)}%` }"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="text-center py-12">
      <i class="fas fa-history text-6xl text-gray-600 mb-4"></i>
      <h3 class="text-xl font-medium text-gray-400 mb-2">暂无播放历史</h3>
      <p class="text-gray-500 mb-4">开始观看视频后，这里会显示您的播放记录</p>
      <router-link to="/" class="btn-primary">
        <i class="fas fa-home mr-2"></i>返回首页
      </router-link>
    </div>

    <!-- 分页 -->
    <div v-if="history.length > itemsPerPage" class="flex justify-center mt-8">
      <div class="flex space-x-2">
        <button
          v-for="page in totalPages"
          :key="page"
          @click="currentPage = page"
          class="px-3 py-1 rounded text-sm"
          :class="currentPage === page ? 'bg-primary-600 text-white' : 'bg-gray-700 text-gray-300 hover:bg-gray-600'"
        >
          {{ page }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useMediaStore } from '../stores/media'
import type { PlaybackHistory } from '../types/media'

const router = useRouter()
const mediaStore = useMediaStore()

// 分页
const currentPage = ref(1)
const itemsPerPage = 20

// 计算属性
const history = computed(() => {
  const allHistory = mediaStore.playbackHistory.map(h => ({
    ...h,
    title: mediaStore.mediaList.find(m => m.id === h.mediaId)?.title || '未知视频',
    url: mediaStore.mediaList.find(m => m.id === h.mediaId)?.url || '',
    duration: mediaStore.mediaList.find(m => m.id === h.mediaId)?.duration,
  }))
  
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return allHistory.slice(start, end)
})

const totalPages = computed(() => 
  Math.ceil(mediaStore.playbackHistory.length / itemsPerPage)
)

const totalWatchTime = computed(() => {
  const total = mediaStore.playbackHistory.reduce((sum, h) => sum + h.lastPosition, 0)
  return formatDuration(total)
})

const todayWatchCount = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return mediaStore.playbackHistory.filter(h => new Date(h.lastPlayed) >= today).length
})

// 方法
const resumePlay = (item: PlaybackHistory & { title: string; url: string; duration?: number }) => {
  const media = mediaStore.mediaList.find(m => m.id === item.mediaId)
  if (media) {
    mediaStore.setCurrentMedia(media)
    router.push('/player')
  }
}

const removeFromHistory = (mediaId: string) => {
  mediaStore.playbackHistory = mediaStore.playbackHistory.filter(h => h.mediaId !== mediaId)
  mediaStore.saveToLocalStorage()
}

const clearHistory = () => {
  if (confirm('确定要清空所有播放历史吗？')) {
    mediaStore.clearHistory()
    mediaStore.saveToLocalStorage()
  }
}

const getProgress = (item: PlaybackHistory & { duration?: number }) => {
  if (!item.duration || item.duration === 0) return 0
  return (item.lastPosition / item.duration) * 100
}

const formatDate = (date: Date): string => {
  const now = new Date()
  const diff = now.getTime() - new Date(date).getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60))
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60))
      return `${minutes}分钟前`
    }
    return `${hours}小时前`
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return new Date(date).toLocaleDateString('zh-CN')
  }
}

const formatTime = (seconds: number): string => {
  if (!seconds || seconds === 0) return '00:00'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}
</script>
